from machine import Pin
import dht


class DHT11Exception(BaseException):
	pass


class DHT11(object):
	"""
	DHT11 驱动
	"""

	def __init__(self, dataline=None):
		assert dataline is not None and isinstance(dataline, int), DHT11Exception("dataline must be a int")

		self.__dht11 = dht.DHT11(Pin(dataline))

	def deinit(self):
		self.__dht11 = None

	def temperature(self):
		"""
		获取温度
		"""
		temperature = -273.15

		try:
			self.__dht11.measure()
			temperature = self.__dht11.temperature()
		except OSError as ose:
			if str(ose) == "[Errno 110] ETIMEDOUT":
				raise DHT11Exception("DHT11 connection error")
		
		return temperature

	def humidity(self):
		"""
		获取湿度
		"""
		humidity = 0

		try:
			self.__dht11.measure()
			humidity = self.__dht11.humidity()
		except OSError as ose:
			if str(ose) == "[Errno 110] ETIMEDOUT":
				raise DHT11Exception("DHT11 connection error")
		
		return humidity

	def temperature_and_humidity(self):
		"""
		获取温湿度
		"""
		result = {"temp": -273.15, "humi": 0}

		try:
			self.__dht11.measure()

			result.update({"temp": self.__dht11.temperature()})
			result.update({"humi": self.__dht11.humidity()})
		except OSError as ose:
			if str(ose) == "[Errno 110] ETIMEDOUT":
				raise DHT11Exception("DHT11 connection error")
		
		return result


def run_test():
	from utime import sleep_ms

	dht11 = DHT11(4)

	print("temperature: {}(°C)".format(dht11.temperature()))
	sleep_ms(1000)

	print("humidity: {}(%)".format(dht11.humidity()))
	sleep_ms(1000)

	print("temperature: {temp}(°C) and humidity: {humi}(%)".format(**dht11.temperature_and_humidity()))

if __name__ == "__main__":
	run_test()
